//
//  FeedbackVC.swift
//  LeTu
//
//  Created by gy on 2023/12/8.
//

import UIKit
import HXPHPicker

class FeedbackVC: BaseViewController {

    private var viewModel = FeedbackVM()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        configUI()
        
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        DispatchQueue.main.async {
            self.commitBtn.layerCornerRadius(self.commitBtn.height/2)
        }
    }
    
    // MARK: - UIButtonAction
    @objc func addPictureBtnAction() {
        AppActionSheet(titles: [AppActionSheetItem(title: "从相册选择".localized), AppActionSheetItem(title: "用相机拍照".localized)]) { [weak self] title, index in
               guard let strongSelf = self else { return }
               
               if title == "从相册选择".localized {
                   // 相册
                   strongSelf.selectImage()
               } else if title == "用相机拍照".localized {
                   // 拍照
                   strongSelf.takePhotos()
               }

        }.show()
    }
    @objc func commitBtnAction() {
        
        guard textView.text.count > 0 else { return Utils.showMessage(message: textView.placeholder) }
        
        showIndicator()
        viewModel.commitFeedback(content: textView.text) { [weak self] dialog in
            guard let strongSelf = self else { return }
            DispatchQueue.main.async {
                strongSelf.hideIndicator()
                strongSelf.showMessage(message: dialog.message)
                if dialog.code == 200 {
                    strongSelf.backAction()
                }
            }
        }
        
    }
    
    // MARK: - configUI
    func configUI() {
     
        navIsHidden = false
        title = "意见反馈".localized
        
        view.addSubview(topLineView)
        view.addSubview(textView)
        view.addSubview(lineView)
        view.addSubview(pictureCollectionView)
        view.addSubview(commitBtn)
        
        topLineView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(10)
        }
        textView.snp.makeConstraints { make in
            make.left.equalTo(24-textView.textContainer.lineFragmentPadding)
            make.right.equalTo(-24)
            make.top.equalTo(topLineView.snp.bottom).offset(26)
            make.height.equalTo(24)
        }
        lineView.snp.makeConstraints { make in
            make.left.right.equalTo(textView)
            make.top.equalTo(textView.snp.bottom).offset(26)
            make.height.equalTo(CGFloat.app_lineHieght)
        }
        pictureCollectionView.snp.makeConstraints { make in
            make.top.equalTo(lineView.snp.bottom).offset(42)
            make.left.equalTo(24)
            make.width.equalTo(screenWidth-24*2)
            make.height.equalTo(84)
        }
        commitBtn.snp.makeConstraints { make in
            make.left.right.equalTo(textView)
            make.top.equalTo(pictureCollectionView.snp.bottom).offset(76)
            make.height.equalTo(CGFloat.app_btnHeight)
        }
        
        pictureCollectionView.delegate = self
        pictureCollectionView.dataSource = self
        pictureCollectionView.register(cellClass: FeedbackPictureCollectionViewCell.self)
        
        commitBtn.addTarget(self, action: #selector(commitBtnAction))
    }
    private lazy var topLineView: UIView = {
        let topLineView = UIView()
        topLineView.backgroundColor = .app_viewBackgroundColor
        return topLineView
    }()
    private lazy var textView: DynamicHeightTextView = {
        let textView = DynamicHeightTextView()
        textView.placeholder = "请输入您的意见或建议".localized
        textView.font = kSetPingFangMedium(14)
        textView.returnKeyType = .done
        return textView
    }()
    private lazy var lineView: UIView = {
        let lineView = UIView()
        lineView.backgroundColor = .app_lineColor
        return lineView
    }()
    private lazy var pictureCollectionView: UICollectionView = {
        let flowlayout = UICollectionViewFlowLayout()
        flowlayout.itemSize = CGSize(width: 84, height: 84)
        flowlayout.minimumLineSpacing = 6
        flowlayout.minimumInteritemSpacing = 6
        let pictureCollectionView = UICollectionView(frame: .zero, collectionViewLayout: flowlayout)
        pictureCollectionView.backgroundColor = .clear
        return pictureCollectionView
    }()
    private lazy var commitBtn: GradientButton = {
        let commitBtn = GradientButton()
        commitBtn.setTitle("提交".localized)
        commitBtn.gradientColors = UIColor.app_themeGradientColors
        commitBtn.setFont(kSetPingFangBlod(15))
        return commitBtn
    }()

}

extension FeedbackVC : TransferEventReceivable {
    
    enum TransferEvent: TransferEventType {
    case delPicture(IndexPath)
    }
    
    func receive(event: TransferEventType) {
        
        switch event {
        case FeedbackVC.TransferEvent.delPicture(let indexPath):
            guard indexPath.item < viewModel.selectPictures.count else { return }
            viewModel.selectPictures.remove(at: indexPath.item)
            viewModel.selectPictureAssets.remove(at: indexPath.item)
            pictureCollectionView.reloadData()
            
        default:
            break
        }
        
    }

}

extension FeedbackVC: PhotoPickerControllerDelegate {
    
    func pickerController(_ pickerController: PhotoPickerController, didFinishSelection result: PickerResult) {
        pickerController.dismiss(animated: true) { [weak self] in
            
            guard let strongSelf = `self` else { return }
            strongSelf.insertPhotos(photoAssets: result.photoAssets)
            
        }
    }
    func pickerController(didCancel pickerController: PhotoPickerController) {
        pickerController.dismiss(animated: true, completion: nil)
    }
    func insertPhotos(photoAssets: [PhotoAsset]) {
        
        self.viewModel.selectPictureAssets = self.viewModel.selectPictureAssets + photoAssets
        self.viewModel.selectPictures = self.viewModel.selectPictures + photoAssets.compactMap { $0.originalImage }
        self.pictureCollectionView.reloadData()
        
    }
    
}


extension FeedbackVC : UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel.selectPictures.count + (viewModel.selectPictures.count < 3 ? 1 : 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(FeedbackPictureCollectionViewCell.self, indexPath: indexPath)
        if indexPath.item == viewModel.selectPictures.count {
            cell.setImg("feedback_add_picture", indexPath: indexPath)
        } else {
            cell.setImg(viewModel.selectPictures[indexPath.item], indexPath: indexPath)
        }
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if indexPath.item == viewModel.selectPictures.count {
            addPictureBtnAction()
        }
        
    }
    
}

extension FeedbackVC : UIImagePickerControllerDelegate , UINavigationControllerDelegate {
    
    // 选择照片
    func selectImage() {
        
        AlbumPermissionsManager.authorizePhotoWith { [weak self] status in
            
            guard let `self` = self else { return }
            
            if (!status) {
                AlbumPermissionsManager.unAuthorizeAlert(vc: self, title: "相册权限未开启" , message: "请在“设置-\(Device.getAppName())”中，允许应用访问你的相册。")
            } else {
                var config: PickerConfiguration = PickerConfiguration()
                config.photoSelectionTapAction = .quickSelect
                config.videoSelectionTapAction = .quickSelect
                config.maximumSelectedCount = 3 - self.viewModel.selectPictures.count
                config.navigationViewBackgroundColor = .white
                config.navigationTintColor = .black
                config.photoList.allowAddCamera = false
                config.photoList.bottomView.previewButtonTitleColor = .app_themeColor
                config.photoList.bottomView.isHiddenOriginalButton = true
                config.photoList.bottomView.finishButtonBackgroundColor = .app_themeColor
                config.photoList.bottomView.finishButtonDisableBackgroundColor = .app_btnDisableColor
                let vc = PhotoPickerController.init(config: config)
                vc.pickerDelegate = self
                vc.autoDismiss = false
                self.present(vc, animated: true, completion: nil)
            }
        
        }

        
    }
    // 拍照
    func takePhotos() {

        AlbumPermissionsManager.authorizeCameraWith { (status) in
            
            if (!status) {
                AlbumPermissionsManager.unAuthorizeAlert(vc: self, title: "相机权限未开启" , message: "请在“设置-\(Device.getAppName())”中，允许应用访问你的相机。")
            } else {
                // 拍照
                //                let config = CameraConfiguration()
                //                config.position = .back
                //                config.appearanceStyle = .dark
                //                config.prefersStatusBarHidden = false
                //                self.present(CameraController(config: config, type: .photo), animated: true, completion: nil)
                
                let  cameraPicker = UIImagePickerController()
                cameraPicker.delegate = self
                cameraPicker.allowsEditing = false
                cameraPicker.sourceType = .camera
                //在需要的地方present出来
                self.present(cameraPicker, animated: true, completion: nil)
            }
            
            
        }
        
        
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        guard let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }
                
        let photoAsset = PhotoAsset(localImageAsset: .init(image: selectedImage))
        insertPhotos(photoAssets: [photoAsset])
        picker.dismiss(animated: true, completion: nil)
        
    }
    
}




